﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Com.Pernix.Component.Member.Models;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace Com.Pernix.Component.Member
{
    public class NHibernateHelper
    {
        private static ISessionFactory _sessionFactory;
        public static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                {
                    var nhConfig = Fluently
                            .Configure()
                            .Database(MsSqlConfiguration
                                       .MsSql2008
                                       .ConnectionString(connstr =>
                                           connstr.FromConnectionStringWithKey("MemberComponent")))
                            .Mappings(mappings => mappings
                                                   .FluentMappings
                                                   .AddFromAssemblyOf<User>()).ExposeConfiguration(x=>x.SetInterceptor(new SqlStatementInterceptor()))
                            .BuildConfiguration();
                    _sessionFactory = nhConfig.BuildSessionFactory();
                    
                }
                return _sessionFactory;
            }
        }

        private static void CreateDatabase()
        {
            Fluently.Configure().Database(MsSqlConfiguration.MsSql2008.ConnectionString(connstr =>
                                           connstr.FromConnectionStringWithKey("MemberComponent"))).Mappings(
                m => m.FluentMappings.AddFromAssemblyOf<User>())
                .ExposeConfiguration(CreateSchema).BuildConfiguration();
        }
        private static void CreateSchema(Configuration cfg)
        {
            var schemaExport = new SchemaExport(cfg);
            schemaExport.Drop(false, true);
            schemaExport.Create(false, true);
        }

        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    }
}
